package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.AutoFillConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Slf4j
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetMealService setMealService;

    @Override
    public Result page(CategoryPageQueryDTO category) {
        PageHelper.startPage(category.getPage(), category.getPageSize());
        Page<Category> page = categoryMapper.page(category);
        return Result.success(new PageResult(page.getTotal(), page.getResult()));
    }

    @Override
    public void allowOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .status(status)
                .id(id)
                .build();
        categoryMapper.update(category);
        log.info("修改状态成功");
    }

    @Override
    public void save(CategoryDTO cateDto) {
        Category category = new Category();
        BeanUtils.copyProperties(cateDto, category);
        // 自动填充公共字段
        category.setStatus(StatusConstant.ENABLE);
        categoryMapper.save(category);
        log.info("新增分类成功");
    }

    @Override
    public void delete(Long id) {
        log.info("删除分类，id：{}", id);
        //启用状态的分类不能删除
        Category category = categoryMapper.getById(id);
        if (category.getStatus() == StatusConstant.ENABLE) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        categoryMapper.delete(id);
    }

    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        log.info("编辑分类：{}", categoryDTO);
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }
}
